import { Reducer } from 'redux';
import { routerRedux } from 'dva/router';
import { Effect } from 'dva';
import { notification } from 'antd';
import {
  orderBuy,
  orderEdit,
  orderList,
  orderDown,
  orderDelete,
  orderSettlement,
  orderProfit,
  soldSearch,
  commodityQuery,
} from '@/services/user';
import { instockUtil, instockSpec } from '@/services/instock';
import { warehourseList } from '@/services/warehourse';

export interface StateType {
  isRefresh?: boolean;
  total?: number;
  list?: Array<any>;
  status?: 'ok' | 'error';
  type?: string;
  currentAuthority?: 'user' | 'guest' | 'admin';
  view?: {};
  personData?: any;
  commodityData?: any;
  hourseData?: any;
  utilsData?: any;
  orderType?: string;
}

export interface LoginModelType {
  namespace: string;
  state: StateType;
  effects: {
    list: Effect;
    down: Effect;
    add: Effect;
    put: Effect;
    view: Effect;
    updateView: Effect;
    edit: Effect;
    delete: Effect;
    soldSearch: Effect;
    commoditySearch: Effect;
    hourseList: Effect;
    // utilsList: Effect;
    settlement: Effect;
    switchStatus: Effect;
    instockSpec: Effect;
    profit: Effect;
  };
  reducers: {
    orderlist: Reducer<StateType>;
    reFresh: Reducer<StateType>;
    redView: Reducer<StateType>;
    redUpdateview: Reducer<StateType>;
    rePerson: Reducer<StateType>;
    reCommodity: Reducer<StateType>;
    reHourse: Reducer<StateType>;
    reUtils: Reducer<StateType>;
    reStatus: Reducer<StateType>;
  };
}

const Model: LoginModelType = {
  namespace: 'order',

  state: {
    orderType: 'settledOrder',
    isRefresh: false,
    total: 0,
    list: [],
    personData: [],
    commodityData: [],
    hourseData: [],
    utilsData: [],
    view: {},
  },

  effects: {
    *put({ payload }, { call, put }) {
      const response = yield call(orderBuy, payload);
      if (response.status == 200) {
        yield put({
          type: 'reFresh',
          payload: true,
        });
      }
    },
    *view({ payload }, { call, put }) {
      yield put({
        type: 'redView',
        payload: payload,
      });
    },
    *updateView({ payload }, { call, put, select }) {
      const view = yield select(({ order }: any) => order.view);
      yield put({
        type: 'redUpdateview',
        payload: { ...view, ...payload },
      });
    },
    *add({ payload }, { call, put }) {
      const response = yield call(orderBuy, payload);
      if (response.status == 200) {
        notification.success({
          message: '订单新增成功',
          description: '',
        });
        yield put({
          type: 'reFresh',
          payload: true,
        });
      }
    },
    *delete({ payload, orderType }, { call, put }) {
      const response = yield call(orderDelete, payload);
      if (response.status == 200) {
        notification.success({
          message: '无效订单生成成功',
          description: '',
        });
        yield put({
          type: 'reStatus',
          payload: orderType,
        });
      }
    },
    *edit({ payload }, { call, put }) {
      const response = yield call(orderEdit, payload);
      if (response.status == 200) {
        notification.success({
          message: '订单修改成功',
          description: '',
        });
        yield put({
          type: 'reFresh',
          payload: true,
        });
      }
    },
    *settlement({ payload, orderType }, { call, put }) {
      const response = yield call(orderSettlement, payload);
      if (response.status == 200) {
        notification.success({
          message: '结算成功',
          description: '',
        });
        yield put({
          type: 'reStatus',
          payload: orderType,
        });
      }
    },
    *list({ payload, orderType }, { call, put }) {
      const response = yield call(orderList, orderType, payload);
      if (response.status == 200) {
        yield put({
          type: 'orderlist',
          payload: response.data,
        });
      }
    },
    *down({ payload, filename }, { call, put }) {
      try {
        const response = yield call(orderDown, payload);
        const blob = new Blob([response], {
          type:
            'application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
        }); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
        const downloadElement = document.createElement('a');
        const href = window.URL.createObjectURL(blob); //创建下载的链接
        downloadElement.href = href;
        downloadElement.download = `${filename}.xlsx`; //下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        window.URL.revokeObjectURL(href); //释放掉blob对象
        // Download(response);
      } catch (error) {}
    },
    *profit({ payload }, { call, put }) {
      try {
        const response = yield call(orderProfit, payload);
        if (response.status == 200) {
          // yield put({
          //   type: 'reFresh',
          //   payload: true,
          // });
          yield put(
            routerRedux.push({
              pathname: '/Profit/company',
            }),
          );
        }
      } catch (error) {}
    },
    *soldSearch({ payload }, { call, put }) {
      const response = yield call(soldSearch, payload);
      if (response.status == 200) {
        yield put({
          type: 'rePerson',
          payload: response.data,
        });
      }
    },
    *hourseList({}, { call, put }) {
      const response = yield call(warehourseList);
      if (response.status == 200) {
        yield put({
          type: 'reHourse',
          payload: response.data,
        });
      }
    },
    // *utilsList({}, { call, put }) {
    //   const response = yield call(instockUtil);
    //   if (response.status == 200) {
    //     yield put({
    //       type: 'reUtils',
    //       payload: response.data,
    //     });
    //   }
    // },
    *instockSpec({ payload }, { call, put }) {
      const response = yield call(instockSpec, payload);
      console.log(response, 333);
      // if (response.status == 200) {
      yield put({
        type: 'reUtils',
        payload: response,
      });
      // }
    },
    *commoditySearch({ payload }, { call, put }) {
      const response = yield call(commodityQuery, payload);
      if (response.status == 200) {
        yield put({
          type: 'reCommodity',
          payload: response.data,
        });
      }
    },
    *switchStatus({ payload }, { call, put }) {
      yield put({
        type: 'reStatus',
        payload: payload,
      });
    },
  },

  reducers: {
    orderlist(state, { payload }) {
      return {
        ...state,
        total: payload.totalElements,
        list: payload.content,
        isRefresh: false,
      };
    },
    redView(state, { payload }) {
      const result: any = {
        ...state,
        view: payload,
      };
      if (payload.staffId) {
        result.personData = [
          { id: payload.staffId, name: payload.staffName, phoneNumber: payload.staffPhoneNum },
        ];
        result.commodityData = [
          { id: payload.wineId, name: payload.wineName, comments: payload.wineDesc },
        ];
        result.utilsData = [{ label: payload.quantityComments, value: payload.quantityUnitId }];
      }
      return result;
    },
    reFresh(state, { payload }) {
      return {
        ...state,
        isRefresh: payload,
      };
    },
    rePerson(state, { payload }) {
      return {
        ...state,
        personData: payload,
      };
    },
    reCommodity(state, { payload }) {
      return {
        ...state,
        commodityData: payload,
      };
    },
    reHourse(state, { payload }) {
      return {
        ...state,
        hourseData: payload,
      };
    },
    reUtils(state, { payload }) {
      return {
        ...state,
        utilsData: payload,
      };
    },
    reStatus(state, { payload }) {
      return {
        ...state,
        orderType: payload,
        isRefresh: true,
      };
    },
    redUpdateview(state, { payload }) {
      return {
        ...state,
        view: payload,
      };
    },
  },
};

export default Model;
